package com.hybench.load;

import java.sql.Connection;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;

public class DataImportFactory {
    public static void loadData(Map<String, String> tableMaps, Connection conn, String dbType) throws Exception {
        DataImport dataImport = loadDataImport(dbType);
        if (!dataImport.needImport()) {
            return;
        }
        for (Map.Entry<String, String> entry: tableMaps.entrySet()) {
            dataImport.doDataImport(conn, entry.getKey(), entry.getValue());
        }
    }
    
    public static DataImport loadDataImport(String dbType) {
        ServiceLoader<DataImport> loader = ServiceLoader.load(DataImport.class);
        List<DataImport> findedDataImport = new LinkedList<>();
        loader.forEach(service -> {
            if (service.getDbType() != null && service.getDbType().equalsIgnoreCase(dbType)) {
                findedDataImport.add(service);
            }
        });
        if (findedDataImport.isEmpty()) {
            System.out.println("failed get autoloader, default will do nothing!");
            return defaultDataImport;
        }
        DataImport first = findedDataImport.get(0);
        if (findedDataImport.size() != 1) {
            System.out.println("find " + findedDataImport.size() + " matched data import, only use first!");
        }
        System.out.println("success get auto loader:" + first.getClass());
        return first;
    }
    
    public static DataImport defaultDataImport = new DataImport() {
        @Override
        public void doDataImport(final Connection conn, final String tableName, final String dataFile) throws Exception {
        
        }
    
        @Override
        public boolean needImport() {
            return false;
        }
    
        @Override
        public String getDbType() {
            return "UNKNOWN";
        }
    };
}
